package com.eric.common.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class GetRoot {

	public static void main(String[] args) throws IOException {
//		String s = args[0];
		String s = "/home/eric/tmp/urls";
		File file = new File(s);
		if (file.exists()) {
			BufferedReader br = new BufferedReader(new FileReader(file));
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File(file.getAbsolutePath()+".root")));
			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(getRoot(line));
				bw.append(getRoot(line));
				bw.append("\n");
			}
			br.close();
			bw.close();
		}else{
			System.out.println(getRoot(s));
		}
	}
	
	public static String getRoot (String url) throws MalformedURLException {
    	URL u = new URL(url.toLowerCase());
    	String host = u.getHost();
    	StringBuffer root = new StringBuffer();
    	String[] rootMembers = host.split("\\.");
    	
    	//一般情况下，取host的最后2个，如www.abc.com取abc.com
    	int n = 2;
    	
    	//判断TLD后缀是否超过1个，比如edu.cn，如果是，则判断域名倒数第2个后缀是否是.com等（.com.cn形式）
    	if (rootMembers.length > 2 ) {
    		String secondLastMember = rootMembers[rootMembers.length - 2];
    		
    		if (secondLastMember.matches("^com$|^net$|^gov$|^edu$|^co$|^org$")) 
    			n = 3;
    	}
    	
    	//确定了n的取数后，将结果保存到StringBuffer中，保存顺序是自左至右
    	for (int i=n;i>0;i--) {
    		try {
    			root.append(rootMembers[host.split("\\.").length-i]);
        		if ((i-1) > 0) root.append(".");
    		}catch (java.lang.ArrayIndexOutOfBoundsException e) {
    			System.out.println("Wrong Url:"+url);
    		}
    	}
    	return root.toString();
    }
}
